package com.itmumu.miniwechat.common.utils;

import com.itmumu.miniwechat.common.constants.RedisKey;
import com.itmumu.miniwechat.user.domain.dto.TokenUserInfoDto;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
public class RedisComponent {

    public TokenUserInfoDto getTokenUserInfoDto(String token) {
        TokenUserInfoDto userInfo = JsonUtils.toObj(RedisUtils.get(RedisKey.getKey(RedisKey.WS_TOKEN + token)), TokenUserInfoDto.class);
        return userInfo;
    }

    public void saveTokenUserInfo(TokenUserInfoDto tokenUserInfoDto) {
        RedisUtils.set(RedisKey.getKey(RedisKey.WS_TOKEN + tokenUserInfoDto.getToken()), tokenUserInfoDto, 3, TimeUnit.HOURS);
        RedisUtils.set(RedisKey.getKey(RedisKey.WS_TOKEN_USERID + tokenUserInfoDto.getUid()), tokenUserInfoDto.getToken(), 3, TimeUnit.HOURS);
    }

    public void saveUserHeartBeat(Integer uid) {
        RedisUtils.set(RedisKey.getKey(RedisKey.USER_HEART_BEAT + uid), Instant.now().getEpochSecond(), 6, TimeUnit.SECONDS);
    }

    public Long getUserHeartBeat(Integer uid) {
        return RedisUtils.get(RedisKey.getKey(RedisKey.USER_HEART_BEAT + uid), Long.class);
    }

    public void cleanUserContact(Integer uid) {
        RedisUtils.del(RedisKey.getKey(RedisKey.REDIS_KEY_USER_CONTACT + uid));
    }

    public void addUserContactBatch(Integer uid, List<Map<String, Integer>> contactIds) {
        RedisUtils.set(RedisKey.getKey(RedisKey.REDIS_KEY_USER_CONTACT + uid), contactIds, 3 * 24 * 60 * 60);
    }

    public List<Map> getUserContactList(Integer userId) {
        return JsonUtils.toList(RedisUtils.get(RedisKey.getKey(RedisKey.REDIS_KEY_USER_CONTACT + userId)), Map.class);
    }
}
